<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="userAccount"
          name="userAccount"
          label="账号"
          placeholder="请输入账号"
          :rules="[{ required: true, message: '请填写账号' }]"
      />
      <van-field
          v-model="userPassword"
          type="password"
          name="userPassword"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="text-align: right; margin-top: 15px;">
      <a style="color: gray; margin-right: 20px; font-size: 15px; :hover {color: dodgerblue}"  @click="toReg">没有账号？点击注册</a>
    </div>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import myAxios from "../plugins/myAxios";
import {Toast} from "vant";

const route = useRoute();
const router = useRouter()

const userAccount = ref('');
const userPassword = ref('');

const onSubmit = async () => {
  const res = await myAxios.post('/user/login', {
    userAccount: userAccount.value,
    userPassword: userPassword.value,
  })
  if (res.code === 0 && res.data) {
    // 跳转到之前的页面
    Toast.success("登录成功！")
    window.location.href = route.query?.redirect as string ?? '/';
  } else {
    Toast.fail('登录失败');
  }
};

const toReg = () => {
  router.push({
    path: '/user/register',
  })
}

</script>

<style scoped>

</style>
